package cn.edu.seu.herald.informationplatform.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.Vote;
import cn.edu.seu.herald.informationplatform.bean.league.VoteItem;
import cn.edu.seu.herald.informationplatform.dao.cookie.LeagueUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteDataAccess;
import cn.edu.seu.herald.informationplatform.dao.database.VoteItemDataAccess;
import cn.edu.seu.herald.informationplatform.filter.LeagueSpecified;

public class VoteDelete extends HttpServlet {

	private static final String SUCCESS_MESSAGE = "操作成功";

	private static final String FAILURE_MESSAGE = "操作失败";
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//参数：无
//功能：删除原来的投票活动，根据链接session获得leagueId，然后删除这个社团的投票
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		try {
			LeagueUserSessionCookieAccess luSessionCookieAccess =
					new LeagueUserSessionCookieAccess(request);
			int leagueId = luSessionCookieAccess.getLeagueId();
			
			VoteDataAccess voteDao = VoteDataAccess.getInstance();
			Vote vote = voteDao.getVoteByLeagueId(leagueId);
			int voteId = vote.getId();
			voteDao.deleteVoteByLeagueId(leagueId);
			
			VoteItemDataAccess voteItemDao = VoteItemDataAccess.getInstance();
			Collection<VoteItem> voteItems =
					voteItemDao.getVoteItemsByVoteId(voteId);
			voteItemDao.deleteVoteItemsByVoteId(voteId);
			
			for (VoteItem voteItem: voteItems) {
				String address = voteItem.getPicture();
				if (address != null) {
					// TODO 删除图片
				}
			}
		} catch (Exception e) {
			printResult(response, FAILURE_MESSAGE);
			return;
		}
		try {
			LeagueUserSessionCookieAccess luSessionCookieAccess =new LeagueUserSessionCookieAccess(request);
			response.sendRedirect("./polling.jsp?league="+luSessionCookieAccess.getLeagueId());
		} catch (Exception e) {
			return;
		}
	}
		
		private void printResult(HttpServletResponse response,
				String msg) throws IOException {
			response.getWriter().println(msg);
		}


}
